package com.octocat.project01.bookstore.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 注意几个细节： 属性、方法、代码块 都是由 static 修饰
 * Author : Octocat
 * Date   : 2021/5/16
 */
public class JdbcUtils {

    private static DruidDataSource druidDataSource;

    static{
        try {
            //Properties类，该类能方便加载配置信息
             Properties properties = new Properties();
             //读取 jdbc.properties 属性配置文件
             InputStream inputStream = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
             //从流中加装数据
             properties.load(inputStream);
            // 创建数据库连接池
            druidDataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取数据库连接池中的连接
     *
     */
    public static Connection getConnection(){
        Connection con = null;
        try {
            con = druidDataSource.getConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return con;
    }

    /**
     * 关闭连接，放回数据库连接池
     */
    public static void close(Connection con){
        if(con != null){
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
